package condition;

import java.util.ArrayList;
import base.Engine;
import base.Piece;
import base.State;
import base.Statistics;
import base.Turn;
import base.VirtualBoard;

public class IsOnMove extends UpgradeRule {
	private ArrayList<String> applicableTypes;
	private Statistics statistics;
	private VirtualBoard board;
	
	private boolean isApplicableType(Piece piece) {
		for (String type : this.applicableTypes) {
			if (piece.getRuleType().equals(type)) {
				return true;
			}
		}
		
		return false;
	}
	
	public IsOnMove(Engine engine, ArrayList<String> applicableTypes) {
		super(engine);
		this.applicableTypes = applicableTypes;
		this.statistics = this.getEngine().getStatistics();
		this.board = statistics.getBoard();
	}
	
	private boolean isDrop(Piece piece, Turn turn) {
		ArrayList<Turn> turns = this.board.getTurns();
		int index = turns.indexOf(turn);
		
		ArrayList<State> changes = turns.get(index - 1).getChanges();
		State lastMove = changes.get(changes.size() - 1);
		
		if (!lastMove.isAlive()) {
			for (State state : turn.getChanges()) {
				if (state.isAlive()) {
					return true;
				}
			}
		}
		
		return false;
	}
	
	@Override
	public boolean isValidUpgrade(Piece piece, String type) {
		if (this.isApplicableType(piece)) {
			Turn lastTurn = this.board.getTurns().get(this.board.getTurns().size() - 1);
			ArrayList<Turn> turns = this.statistics.getTurnsByPiece(piece);
			return lastTurn == turns.get(turns.size() - 1) && !this.isDrop(piece, lastTurn);
		}
		else {
			return true;
		}
	}
}
